package com.hk.core.autoconfigure.exception.reactive;

import com.hk.commons.JsonResult;
import com.hk.commons.util.SpringContextHolder;
import com.hk.core.authentication.api.AuthenticationException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * spring security 异常处理器
 *
 * @author kevin
 * @date 2018-09-10 14:17
 */
@RestControllerAdvice
public class SpringSecurityExceptionHandler extends AbstractExceptionHandler {

    /**
     * 无权限访问
     *
     * @param e        e
     * @param exchange exchange
     * @return jsonResult
     */
    @ExceptionHandler(value = {AccessDeniedException.class})
    @ResponseStatus(HttpStatus.OK)
    public Mono<JsonResult<Void>> accessDeniedException(AccessDeniedException e, ServerWebExchange exchange) {
        error(e, e.getMessage(), exchange);
        return Mono.just(JsonResult.forbidden(SpringContextHolder.getMessage("no.permission.access.message")));
    }

    @ExceptionHandler(value = AuthenticationException.class)
    @ResponseStatus(HttpStatus.OK)
    public Mono<JsonResult<Void>> authenticationException(AuthenticationException e, ServerWebExchange exchange) {
        error(e, e.getMessage(), exchange);
        return Mono.just(JsonResult.unauthorized(SpringContextHolder.getMessage("operation.unauthorized")));
    }
}
